#include "cadreinfo.h"
#include "ui_cadreinfo.h"
#include <QDebug>
#include <QString>
#include <QTableView>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>
#include <QDate>
#include <QSqlTableModel>
#include <QMessageBox>
#include <QSqlError>
#include <QDialog>
#include <QDialogButtonBox>
#include <QTextDocument>
#include <QPrinter>
#include <QTextBlock>
#include <QFileDialog>
#include <QFile>
#include <QFileDialog>

CadreInfo::CadreInfo(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CadreInfo)
{
    cadreModel = new QSqlQueryModel(this);
    ui->setupUi(this);
    departList = new DepartList(this);
    departList->hide();
    cadreoverviewtab = new CadreOverviewTab(this);
    cadreinfotab = new CadreInfoTab(this);
    cadrefamilytab = new CadreFamilyTab(this);
    cadreedutab1 = new CadreEduTab(this);
    cadreedutab2 = new CadreEduTab(this);
    cadretitletab = new CadreTitleTab(this);
    cadretraintab = new CadreTrainTab(this);
    cadrerewardtab = new CadreRewardTab(this);
    cadrepunishtab = new CadrePunishTab(this);
    cadreposttab = new CadrePostTab(this);
    cadrechecktab = new CadreCheckTab(this);
    initTableView();
    QSqlRecord xinxidata = cadreModel->record(lastIndex);
    cadreinfotab->initXinXiTab(xinxidata);
    allTabFresh(currentPerson);
    // 如果"信息"tab的index变了，一定记得去on_addButton_clicked()中修改一致
    ui->tabWidget_2->insertTab(0,cadreoverviewtab,QString::fromUtf8("总览"));
    ui->tabWidget_2->insertTab(1,cadreinfotab,QString::fromUtf8("信息"));
    ui->tabWidget_2->insertTab(3,cadreposttab,QString::fromUtf8("职务"));
    ui->tabWidget_2->insertTab(4,cadrefamilytab,QString::fromUtf8("家庭"));
    ui->tabWidget_2->insertTab(5,cadreedutab1,QString::fromUtf8("全日制学历"));
    ui->tabWidget_2->insertTab(6,cadreedutab2,QString::fromUtf8("在职学历"));
    ui->tabWidget_2->insertTab(7,cadretitletab,QString::fromUtf8("职称"));
    ui->tabWidget_2->insertTab(8,cadretraintab,QString::fromUtf8("培训"));
    ui->tabWidget_2->insertTab(9,cadrerewardtab,QString::fromUtf8("奖励"));
    ui->tabWidget_2->insertTab(10,cadrepunishtab,QString::fromUtf8("惩处"));
    ui->tabWidget_2->insertTab(11,cadrechecktab,QString::fromUtf8("考核"));
    ui->tabWidget_2->setCurrentIndex(0);
}

CadreInfo::~CadreInfo()
{
    delete ui;
}
// 所有tab  刷新
void CadreInfo::allTabFresh(QString currentPerson)
{
    cadreoverviewtab->initOverviewTab(currentPerson);
    cadrefamilytab->initFamilyTableView(currentPerson);
    cadreedutab1->initEduTableView(currentPerson,"1");
    cadreedutab2->initEduTableView(currentPerson,"0");
    initExperTableView();
    cadretitletab->initTitleTableView(currentPerson);
    cadretraintab->initTrainTableView(currentPerson);
    cadrerewardtab->initRewardTableView(currentPerson);
    cadrepunishtab->initPunishTableView(currentPerson);
    cadreposttab->initPostTableView(currentPerson);
    cadrechecktab->initCheckTableView(currentPerson);
    departList->initTree(currentPerson);
}
QString CadreInfo::getSql()
{
    QString sql = "SELECT `CadreName`, `UsedName`, `CredTypeID`, `IDNum`, `Birth`, "
                  "`JoinWorkTime`, `Sex`, `Health`, `NationID`, `NativePlace`, "
                  "`BirthPlace`, `GrowPlace`, `PoliticID`, `PartyTime`, `DemoParty`, "
                  "`RetireChange`, `Speciality`, `ManageStatusID`, `IdenCate`, `ThreeOne`, "
                  "`Phone`, `SubstratumWork`, ci.`UnitID`, `RankID`, `RankTime`, `RankSalary`, "
                  "`Photo`, `MaritalStatusID` FROM CadreInfo ci ";
    QString name = ui->namelineEdit->text();
    QString unit = ui->unitlineEdit->text();
    if(!name.isEmpty()&& unit.isEmpty())
    {
         sql+= QString("where `CadreName` like '%%1%' ").arg(name);
    }
    if (name.isEmpty()&& !unit.isEmpty())
    {
        sql+=QString("left join unit on unit.unitid=ci.`UnitID` "
             "where unit.unitname like '%%1%'").arg(unit);
    }
    if(!name.isEmpty()&& !unit.isEmpty())
    {
        sql+=QString("left join unit on unit.unitid=ci.`UnitID` "
              "where `CadreName` like '%%1%' "
              "and unit.unitname like '%%2%' ").arg(name,unit);
    }
    return sql;
}

void CadreInfo::initTableView()
{
    QString sql = getSql();
    cadreModel->setQuery(sql);
    cadreModel->setHeaderData(0, Qt::Horizontal, QString::fromUtf8("姓名"));
    cadreModel->setHeaderData(4, Qt::Horizontal, QString::fromUtf8("生日"));
    int count = cadreModel->rowCount();
    ui->tableView->setModel(cadreModel);
    TimeEditDelegate *birthtime = new TimeEditDelegate();
    ui->tableView->setItemDelegateForColumn(4,birthtime);
    ui->tableView->setColumnWidth(4,140);
    for(int i=0;i<cadreModel->columnCount();i++){
        if(i==0||i==4){
        }else{
            ui->tableView->setColumnHidden(i,true);
        }
    }
    lastIndex = count-1;
    curRow = lastIndex;
    currentPerson=cadreModel->record(lastIndex).value("IDNum").toString();
    ui->tableView->selectRow(lastIndex);
    // 页面上方菜单中的内容
    ui->cadrenamelabel->setText(cadreModel->record(lastIndex).value("CadreName").toString());
    ui->totalindex->setText(QString("/")+QString::number(count));
    ui->nowindex->setText(QString::number(count));

}

void CadreInfo::on_comboBox_currentIndexChanged(const QString &arg1)
{
    QString item = arg1;
    ui->tabWidget->setTabText(0,item);
    if (item == QString::fromUtf8("干部列表")){
        ui->tabWidget->removeTab(0);
        ui->tabWidget->addTab(ui->tableView,QString::fromUtf8("干部列表"));
    }
    if (item == QString::fromUtf8("单位列表")){
        ui->tabWidget->removeTab(0);        
        ui->tabWidget->addTab(departList,QString::fromUtf8("单位列表"));
    }
}
// 锁定/编辑按钮,涉及所有tab中的按钮
void CadreInfo::on_lockButton_clicked()
{
    QString text = ui->lockButton->text();
    if(text==QString::fromUtf8("锁定(F1)")){
        ui->lockButton->setText(QString::fromUtf8("编辑(F1)"));
        ui->addButton->setEnabled(false);
        ui->deleteButton->setEnabled(false);
        cadreinfotab->setEditStatus(false);
        //工作经历表按钮组
        ui->experAddButton->setEnabled(false);
        ui->experCopyButton->setEnabled(false);
        ui->experDeleteButton->setEnabled(false);
        ui->experDownButton->setEnabled(false);
        ui->experUpButton->setEnabled(false);
        ui->experTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
        // 家庭按钮组
        cadrefamilytab->setButtonEnable(false);
        // 学历按钮组
        cadreedutab1->setButtonEnable(false);
        cadreedutab2->setButtonEnable(false);
        // 其他tab按钮组
        cadretitletab->setButtonEnable(false);
        cadretraintab->setButtonEnable(false);
        cadrerewardtab->setButtonEnable(false);
        cadrepunishtab->setButtonEnable(false);
        cadreposttab->setButtonEnable(false);
        cadrechecktab->setButtonEnable(false);
        // 编辑保存
        bool result;
        if(opFlag=="edit"){
            result = cadreinfotab->updateOrAddXinxi("update",currentPerson);
        }
        if(opFlag=="add"){
            result = cadreinfotab->updateOrAddXinxi("add",currentPerson);
        }
        if (result){
            // 新增成功后，全面刷新 ！！！！！！
            initTableView();
            int addIndex;  //addIndex 是新加干部所在行,
            for(int i=0;i<=lastIndex;i++){
                if(cadreModel->record(i).value("IDNum")==cadreinfotab->addPerson){
                    addIndex=i;
                    currentPerson=cadreinfotab->addPerson;
                    ui->tableView->selectRow(addIndex);
                    curRow = addIndex;
                    QSqlRecord xinxidata = cadreModel->record(addIndex);
                    cadreinfotab->initXinXiTab(xinxidata);
                    allTabFresh(currentPerson);
                }
            }
        }
        if(result==false){
            on_lockButton_clicked();
        }

    }else {
        ui->lockButton->setText(QString::fromUtf8("锁定(F1)"));
        opFlag="edit";
        ui->addButton->setEnabled(true);
        ui->deleteButton->setEnabled(true);
        cadreinfotab->setEditStatus(true);
        ui->experAddButton->setEnabled(true);
        ui->experCopyButton->setEnabled(true);
        ui->experDeleteButton->setEnabled(true);
        ui->experDownButton->setEnabled(true);
        ui->experUpButton->setEnabled(true);
        ui->experTableView->setEditTriggers(QAbstractItemView::DoubleClicked);
        cadrefamilytab->setButtonEnable(true);
        cadreedutab1->setButtonEnable(true);
        cadreedutab2->setButtonEnable(true);
        cadretitletab->setButtonEnable(true);
        cadretraintab->setButtonEnable(true);
        cadrerewardtab->setButtonEnable(true);
        cadrepunishtab->setButtonEnable(true);
        cadreposttab->setButtonEnable(true);
        cadrechecktab->setButtonEnable(true);
    }
}

void CadreInfo::on_tableView_clicked(const QModelIndex &index)
{
    QSqlRecord rowData = cadreModel->record(index.row());
    currentPerson = rowData.value("IDNum").toString();
    curRow= index.row();
    ui->tableView->selectRow(curRow);
    ui->cadrenamelabel->setText(rowData.value("CadreName").toString());
    ui->nowindex->setText(QString::number(index.row()+1));
    cadreinfotab->initXinXiTab(rowData);
    allTabFresh(currentPerson);
}

// 删除
void CadreInfo::on_deleteButton_clicked()
{
    QSqlQuery query = cadreModel->query();
    QString sql = QString::fromUtf8("delete from CadreInfo where IDNum='%1'").arg(currentPerson);
    if(query.exec(sql)) {
        initTableView();
        QSqlRecord xinxidata = cadreModel->record(lastIndex);
        cadreinfotab->initXinXiTab(xinxidata);
        allTabFresh(currentPerson);
    }else {
        QMessageBox::information(this,trUtf8("操作提示"),
            trUtf8("操作失败"),QMessageBox::Yes);
    }

}

// 增加
void CadreInfo::on_addButton_clicked()
{
    opFlag="add";
    ui->tabWidget_2->setCurrentIndex(1);
    cadreinfotab->clearXinxiContent();
    cadreinfotab->setEditStatus(true);
}

void CadreInfo::on_searchpushButton1_clicked()
{
   initTableView();
   QSqlRecord xinxidata = cadreModel->record(lastIndex);
   cadreinfotab->initXinXiTab(xinxidata);
   allTabFresh(currentPerson);
}
void CadreInfo::on_tabWidget_2_currentChanged(int /*index*/)
{
    QSqlRecord xinxidata = cadreModel->record(curRow);
    cadreinfotab->initXinXiTab(xinxidata);
    currentPerson= xinxidata.value("IDNum").toString();
    allTabFresh(currentPerson);
}
// 输出
void CadreInfo::on_outpushButton_clicked()
{
    QString pdfname = QFileDialog::getSaveFileName( this, "Save", "", "*.pdf" );
    QFile file( pdfname );
    if( !file.open(QFile::WriteOnly | QFile::Text) )
    {
        return;
    }
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(pdfname);
    QTextDocument document;
    QString html = cadreoverviewtab->saveHtmlToPDF();
    document.setHtml(html);
    document.print(&printer);
    document.end();
}

// 工作经历相关方法-------------------------------------------------------------------------------
// 工作经历相关方法-------------------------------------------------------------------------------

void CadreInfo::initExperTableView()
{
    experModel = new QSqlTableModel(this);
    experModel->setTable("Experience");
    //setEditStrategy配置很重要，直接影响操作的提交方式
    experModel->setEditStrategy(QSqlTableModel::OnFieldChange);// OnRowChange OnFieldChange OnManualSubmit
    QString filter = QString::fromUtf8("IDNum='%1'").arg(currentPerson);
    experModel->setFilter(filter);
    experModel->select();
    experModel->setHeaderData(1, Qt::Horizontal, QString::fromUtf8("开始时间"));
    experModel->setHeaderData(2, Qt::Horizontal, QString::fromUtf8("结束时间"));
    experModel->setHeaderData(3, Qt::Horizontal, QString::fromUtf8("单位名称"));
    experModel->setHeaderData(4, Qt::Horizontal, QString::fromUtf8("曾经从事工作或担任职务"));
    ui->experTableView->horizontalHeader()->setVisible(true); //UI界面设置，总是恢复为false
    ui->experTableView->setModel(experModel);
    TimeEditDelegate *starttime = new TimeEditDelegate();
    TimeEditDelegate *endtime = new TimeEditDelegate();
    ui->experTableView->setItemDelegateForColumn(1,starttime);
    ui->experTableView->setItemDelegateForColumn(2,endtime);
    ui->experTableView->setColumnHidden(0,true);
    ui->experTableView->setColumnWidth(1,120);
    ui->experTableView->setColumnWidth(2,120);
    ui->experTableView->setColumnWidth(3,260);
    ui->experTableView->setColumnWidth(4,400);
    ui->experTableView->setColumnHidden(5,true);
    ui->experTableView->selectRow(experModel->rowCount()-1);
}
// 添加行
void CadreInfo::on_experAddButton_clicked()
{
    QDialog *addDialog = new QDialog(this);
    addDialog->setWindowTitle(trUtf8("添加工作经历"));
    addDialog->setGeometry(700,300,500,350);
    QGridLayout *gridLayout = new QGridLayout(addDialog);
    gridLayout->setMargin(10);
    QLabel *startLabel =new QLabel(trUtf8("开始时间"),addDialog);
    QLabel *endLabel=new QLabel(trUtf8("结束时间"),addDialog);
    QLabel *unitLabel=new QLabel(trUtf8("单位名称"),addDialog);
    QLabel *postLabel=new QLabel(trUtf8("曾经从事工作或担任职务"),addDialog);
    CDateEdit *starttime=new CDateEdit(addDialog);
    starttime->setNullable(true);
    starttime->setDisplayFormat("yyyy-MM-dd");
    starttime->setCalendarPopup(true);
    starttime->setDate(QDate());
    CDateEdit *endtime = new CDateEdit(addDialog);
    endtime->setNullable(true);
    endtime->setDisplayFormat("yyyy-MM-dd");
    endtime->setCalendarPopup(true);
    endtime->setDate(QDate());
    QLineEdit *unit = new QLineEdit(addDialog);
    QLineEdit *post = new QLineEdit(addDialog);
    gridLayout->addWidget(startLabel,0,0);
    gridLayout->addWidget(starttime,0,1);
    gridLayout->addWidget(endLabel,1,0);
    gridLayout->addWidget(endtime,1,1);
    gridLayout->addWidget(unitLabel,2,0);
    gridLayout->addWidget(unit,2,1);
    gridLayout->addWidget(postLabel,3,0);
    gridLayout->addWidget(post,3,1);

    QPushButton *yesButton = new QPushButton(trUtf8("确定"));
    QPushButton *cancelButton = new QPushButton(trUtf8("取消"));

    QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal);
    buttonBox->addButton(yesButton, QDialogButtonBox::AcceptRole);
    buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);

    gridLayout->addWidget(buttonBox,4,0,1,2,Qt::AlignHCenter);

    connect(buttonBox, SIGNAL(accepted()), addDialog, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), addDialog, SLOT(reject()));

    if(addDialog->exec()==QDialog::Accepted){
        QSqlQuery query;
        query.prepare("insert into Experience (`StartTime`, `EndTime`, `UnitName`, `PostName`, `IDNum`)"
                      " values(:starttime, :endtime, :unit, :post, :idnum )");
        query.bindValue(":starttime",starttime->date());
        query.bindValue(":endtime",endtime->date());
        query.bindValue(":unit",unit->text());
        query.bindValue(":post",post->text());
        query.bindValue(":idnum",currentPerson);
        if(query.exec()){
            QMessageBox::information(this,trUtf8("提示"),
               trUtf8("插入数据成功"),QMessageBox::Yes);
            initExperTableView();
        }else{
            QString info = query.lastError().databaseText();
            QMessageBox::information(this,trUtf8("插入数据库错误"),
               info,QMessageBox::Yes);
        }

    }else{

    }

}

// 删除行
void CadreInfo::on_experDeleteButton_clicked()
{
    int index=ui->experTableView->currentIndex().row();
    int ok = QMessageBox::warning(this,trUtf8("删除当前行!"),
                                   trUtf8("你确定删除当前行吗？"),
                          QMessageBox::Yes,QMessageBox::No);
     if(ok == QMessageBox::Yes)
     {
         experModel->removeRow(index);
         ui->experTableView->selectRow(experModel->rowCount()-1);
     }else{

     }
}

// 移动行的公共方法
void CadreInfo::moveRow(QSqlTableModel *model, int curRow, int toRow){

    if(curRow == toRow)
         return;

    int row;

    if(curRow>toRow){
        row = curRow;
        curRow = toRow;
        toRow = row;
    }
    QSqlRecord curRecord= model->record(curRow);
    QString curId= curRecord.field(0).value().toString();
    QSqlRecord toRecord= model->record(toRow);
    QString toId = toRecord.field(0).value().toString();
    model->removeRows(curRow,2); //挨着的两行
    model->insertRow(curRow);
    model->setRecord(curRow,toRecord);
    model->setData(model->index(curRow,0),curId);
    model->insertRow(toRow);
    model->setRecord(toRow,curRecord);
    model->setData(model->index(toRow,0),toId);
    model->submitAll();
}
// 上移,实现过程：两行数据拿出来，删除两行，插入row,插入record,修改ID。
void CadreInfo::on_experUpButton_clicked()
{
    int curRow = ui->experTableView->currentIndex().row();
    if(curRow==0){
        QMessageBox::information(this,trUtf8("上移操作提示"),
            trUtf8("当前第一行，不能进行上移操作"),QMessageBox::Yes);
        return;
    }
    // 没有选中任何一行
    if(curRow==-1){
        QMessageBox::information(this,trUtf8("操作提示"),
            trUtf8("没有选中任何一行，不能进行操作"),QMessageBox::Yes);
        return;
    }
    moveRow(experModel,curRow,curRow-1);
    ui->experTableView->selectRow(curRow-1);
}
// 下移,实现过程：两行数据拿出来，删除两行，插入row,插入record,修改ID。
void CadreInfo::on_experDownButton_clicked()
{
    int curRow = ui->experTableView->currentIndex().row();
    int total = experModel->rowCount();
    if(curRow==total-1){
        QMessageBox::information(this,trUtf8("操作提示"),
            trUtf8("当前最后一行，不能进行下移操作"),QMessageBox::Yes);
        return;
    }
    if(curRow==-1){
        QMessageBox::information(this,trUtf8("操作提示"),
           trUtf8("没有选中任何一行，不能进行操作"),QMessageBox::Yes);
        return;
    }
    moveRow(experModel,curRow,curRow+1);
    ui->experTableView->selectRow(curRow+1);
}
// 将信息复制到粘贴板
//void CadreInfo::on_experCopyButton_clicked()
//{
//    QString source =
//    QClipboard *clipboard = QApplication::clipboard();   //获取系统剪贴板指针
//    clipboard->setText(source);
//}



